package Offer2017;

/**
 * @leiwenkang 2018-01-11 12:53.
 */
public class InsertSort {
    public static void main(String[] args) {
        int[] array = {2, 5, 3, 9, 7, 6, 8, 1, 4};
        insertSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            System.out.print(" ");
        }
    }


    public static void insertSort(int[] array){
        if (array == null || array.length == 0){
            return;
        }

        for (int i = 1; i < array.length; i++) {
            if (array[i] < array[i - 1]) {
                int val = array[i];
                int j;
                for (j = i - 1; j >= 0 && array[j] >= val; j--) {
                    array[j + 1] = array[j];
                }
                array[j + 1] = val;
            }
        }
    }
}
